package com.example.actflow.fragment;


import android.accessibilityservice.AccessibilityServiceInfo;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityManager;
import android.widget.*;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.example.actflow.MainActivity;
import com.example.actflow.R;
import com.example.actflow.model.AppInfo;
import com.example.actflow.model.Appconfig;
import com.example.actflow.repository.ContextData;

import java.util.*;
import java.util.stream.Collectors;

public class AppListFragment extends Fragment {

    private LinearLayout appItemsContainer;
    private Button addAppBtn;

    private ContextData contextData;
    private List<AppInfo> appInfoList;

    private AppInfo dialogAppInfo;

    private Switch asSwitch;


    // 用接口通知 MainActivity 更新 Spinner 和流程配置
    public interface OnAppListChangedListener {
        void onAppListChanged(AppInfo appInfo);
    }

    private OnAppListChangedListener listener;

    public void setOnAppListChangedListener(OnAppListChangedListener listener) {
        this.listener = listener;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_app_list, container, false);

        appItemsContainer = root.findViewById(R.id.appItemsContainer);
        addAppBtn = root.findViewById(R.id.addAppBtn);

        contextData = ContextData.getInstance(getContext());
        appInfoList = contextData.getAllInstalledAppInfo();

        // 初始化已经添加的应用列表
        for (Appconfig config : contextData.getAppConfigs()) {
            if (config.appInfo != null) {
                addAppItem(config.appInfo);
            }
        }

        addAppBtn.setOnClickListener(v -> showAddAppDialog());


        asSwitch = root.findViewById(R.id.as_status);
        asSwitch.setChecked(isAccessibilityServiceEnabled());
        asSwitch.setOnClickListener((e) -> {
            if (asSwitch.isChecked()) {
                if (!isAccessibilityServiceEnabled()) {
                    asSwitch.setChecked(false);
                    openAccessibilitySettings();
                }
            }

        });


        return root;
    }

    private boolean isAccessibilityServiceEnabled() {
        if (getContext() == null) return false;

        AccessibilityManager am = (AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);

        if (am == null) return false;

        List<AccessibilityServiceInfo> enabledServices = am.getEnabledAccessibilityServiceList(
                AccessibilityServiceInfo.FEEDBACK_ALL_MASK);

        for (AccessibilityServiceInfo enabledService : enabledServices) {
            if (enabledService.getId().startsWith(getContext().getPackageName())) {
                return true;
            }
        }
        return false;
    }

    private final ActivityResultLauncher<Intent> accessibilitySettingsLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                // 用户从设置返回时回调
                if (asSwitch != null) {
                    asSwitch.setChecked(isAccessibilityServiceEnabled());
                }
            });

    private void openAccessibilitySettings() {
        Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
        accessibilitySettingsLauncher.launch(intent);
        Toast.makeText(getContext(), "请先开启无障碍服务", Toast.LENGTH_SHORT).show();

    }


    private void addAppItem(AppInfo appInfo) {
        String packageName = appInfo.packageName;
        String appName = appInfo.appName;

        View appItem = LayoutInflater.from(getContext()).inflate(R.layout.app_item, appItemsContainer, false);
        appItem.setTag(packageName);

        Button openAppBtn = appItem.findViewById(R.id.openAppBtn);
        Button editFlowBtn = appItem.findViewById(R.id.editFlowBtn);
        Button removeBtn = appItem.findViewById(R.id.removeBtn);
        TextView appName_ = appItem.findViewById(R.id.appName);
        TextView appPackage = appItem.findViewById(R.id.appPackage);

        appName_.setText(appName);
        appPackage.setText(packageName);

        openAppBtn.setOnClickListener(v -> {
            if (getActivity() instanceof MainActivity) {
                ((MainActivity) getActivity()).launchApp(packageName);
            }
        });

        editFlowBtn.setOnClickListener(v -> {
            if (getActivity() instanceof MainActivity) {
                contextData.selectedAppInfo = appInfo;
                if (listener != null) {
                    Optional<Appconfig> first = contextData.getAppConfigs().stream().filter(d -> d.appInfo.packageName.equals(packageName)).findFirst();
                    first.ifPresent(appconfig -> listener.onAppListChanged(appconfig.appInfo));

                }
            }
        });

        removeBtn.setOnClickListener(v -> {
            appItemsContainer.removeView(appItem);
            contextData.removeAppConfig(packageName);
            if (listener != null) {
                listener.onAppListChanged(null); // 通知MainActivity更新
            }
        });

        appItemsContainer.addView(appItem);
    }

    private void showAddAppDialog() {
        AutoCompleteTextView autoCompleteTextView = getAutoCompleteTextView();

        AlertDialog alertDialog = new AlertDialog.Builder(getContext())
                .setTitle("添加应用")
                .setView(autoCompleteTextView)
                .setPositiveButton("确定", null) // 先设为 null，后面手动处理点击
                .setNegativeButton("取消", (d, which) -> d.dismiss())
                .create();

        alertDialog.setOnShowListener(dialog -> {
            Button positiveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
            positiveButton.setOnClickListener(v -> {
                String inputText = autoCompleteTextView.getText().toString().trim();

                if (inputText.isEmpty()) {
                    autoCompleteTextView.setError("请输入应用名称");
                    return;
                }
                String appName = dialogAppInfo.appName;
                String packageName = dialogAppInfo.packageName;
                if (!inputText.equals(appName)) {
                    autoCompleteTextView.setError("请选择列表中的应用");
                    return;
                }

                // 校验通过，关闭对话框
                alertDialog.dismiss();

                AppInfo appInfo = new AppInfo(packageName, appName);
                contextData.addAppConfig(new Appconfig(appInfo));
                addAppItem(appInfo);

                if (listener != null) {
                    contextData.selectedAppInfo = appInfo;
                    listener.onAppListChanged(appInfo);
                }
            });
        });

        alertDialog.show();
    }


    private AutoCompleteTextView getAutoCompleteTextView() {
        AutoCompleteTextView autoCompleteTextView = new AutoCompleteTextView(getContext());

        // 过滤已使用的app
        Set<String> usedPackages = contextData.getAppConfigs().stream().filter(d -> d.appInfo != null).map(d -> d.appInfo.packageName).collect(Collectors.toSet());
        List<AppInfo> filteredList = appInfoList.stream()
                .filter(app -> !usedPackages.contains(app.packageName))
                .collect(Collectors.toList());

        ArrayAdapter<AppInfo> adapter = new ArrayAdapter<>(getContext(),
                android.R.layout.simple_dropdown_item_1line, new ArrayList<>(filteredList)) {

            @NonNull
            @Override
            public View getView(int position, View convertView, @NonNull ViewGroup parent) {
                if (convertView == null) {
                    convertView = LayoutInflater.from(getContext())
                            .inflate(android.R.layout.simple_list_item_2, parent, false);
                }
                TextView text1 = convertView.findViewById(android.R.id.text1);
                TextView text2 = convertView.findViewById(android.R.id.text2);

                AppInfo app = getItem(position);
                if (app != null) {
                    text1.setText(app.appName);
                    text2.setText(app.packageName);
                }
                return convertView;
            }

            @Override
            public Filter getFilter() {
                return new Filter() {
                    @Override
                    protected FilterResults performFiltering(CharSequence constraint) {
                        FilterResults results = new FilterResults();
                        List<AppInfo> filtered = new ArrayList<>();

                        if (constraint == null || constraint.length() == 0) {
                            filtered.addAll(filteredList);
                        } else {
                            String query = constraint.toString().toLowerCase();
                            for (AppInfo app : filteredList) {
                                if (app.appName.toLowerCase().contains(query) || app.packageName.toLowerCase().contains(query)) {
                                    filtered.add(app);
                                }
                            }
                        }
                        results.values = filtered;
                        results.count = filtered.size();
                        return results;
                    }

                    @Override
                    protected void publishResults(CharSequence constraint, FilterResults results) {
                        clear();
                        if (results.values != null) {
                            addAll((List<AppInfo>) results.values);
                        }
                        notifyDataSetChanged();
                    }

                    @Override
                    public CharSequence convertResultToString(Object resultValue) {
                        AppInfo app = (AppInfo) resultValue;
                        dialogAppInfo = app;
                        return app.appName;
                    }
                };
            }
        };

        autoCompleteTextView.setAdapter(adapter);
        autoCompleteTextView.setThreshold(0);

        autoCompleteTextView.setOnItemClickListener((parent, view, position, id) -> {
            AppInfo app = (AppInfo) parent.getItemAtPosition(position);
            dialogAppInfo = app;
        });

        autoCompleteTextView.setOnClickListener(v -> {
            if (!autoCompleteTextView.isPopupShowing()) {
                autoCompleteTextView.showDropDown();
            }
        });

        return autoCompleteTextView;
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String status = intent.getStringExtra("status");

            if (status != null && asSwitch != null) {
                asSwitch.setChecked(status.equals("true"));
            }
        }
    };

    @Override
    public void onStart() {
        super.onStart();
        IntentFilter filter = new IntentFilter("AS_BROADCAST");
        if (getContext() != null) {
            LocalBroadcastManager.getInstance(getContext()).registerReceiver(receiver, filter);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (getContext() != null) {
            LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(receiver);
        }
    }
}
